﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace block_explorer
{
    class OrientableCamera : SceneCamera
    {
        private Quaternion mOrientation;

        private Vector3 mXAxis;
        private Vector3 mYAxis;
        private Vector3 mZAxis;
        
        private Vector3 mViewDir;

        public Vector3 Direction { get { return mViewDir; } }
        public Quaternion Orientation { get { return mOrientation; } set { mOrientation = value; mViewMatrixDirty = true; } }

        public OrientableCamera(int viewWidth, int viewHeight, float fov, float near, float far)
            :base(viewWidth, viewHeight, fov, near, far)
        {
            mOrientation = Quaternion.Identity;
        }

        protected override void UpdateViewMatrix()
        {
            Matrix view;// = View;
            Matrix.CreateFromQuaternion(ref mOrientation, out view);

            mXAxis.X = view.M11;
            mXAxis.Y = view.M21;
            mXAxis.Z = view.M31;

            mYAxis.X = view.M12;
            mYAxis.Y = view.M22;
            mYAxis.Z = view.M32;

            mZAxis.X = view.M13;
            mZAxis.Y = view.M23;
            mZAxis.Z = view.M33;

            view.M41 = -Vector3.Dot(mXAxis, Position);
            view.M42 = -Vector3.Dot(mYAxis, Position);
            view.M43 = -Vector3.Dot(mZAxis, Position);

            mViewDir.X = -mZAxis.X;
            mViewDir.Y = -mZAxis.Y;
            mViewDir.Z = -mZAxis.Z;

            View = view;
        }
    }
}
